package com.example.homework

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.homework.db.UserDBHelper
import com.example.homework.model.User
import com.example.homework.utils.RankUtils
import kotlin.math.atan2
import kotlin.math.hypot

class GameActivity : AppCompatActivity() {

    private lateinit var gameView: GameView
    private lateinit var tvScore: TextView
    private lateinit var tvCountdown: TextView
    private lateinit var btnBoost: ImageButton
    private lateinit var username: String
    private lateinit var account: String
    private lateinit var dbHelper: UserDBHelper
    private var isThreadRunning = true

    // 倒计时变量
    private var countdownSeconds = 60 // 初始60秒
    private var countdownThread: Thread? = null
    private var user: User? = null

    // 摇杆变量
    private var joystickIsDragging = false
    private var joystickBgCenterX = 0f
    private var joystickBgCenterY = 0f
    private val joystickBgRadius = 100f
    private lateinit var joystickBg: View
    private lateinit var joystickBall: View
    private val joystickBallRadius get() = joystickBall.width / 2f
    private val maxBallDistance get() = joystickBgRadius - joystickBallRadius

    @SuppressLint("SetTextI18n", "ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.hide()
        setContentView(R.layout.activity_game)

        // 获取传递的用户信息
        account = intent.getStringExtra("account") ?: ""
        username = intent.getStringExtra("username") ?: ""
        dbHelper = UserDBHelper(this)
        user = dbHelper.getUserByAccount(account)

        // 绑定视图
        gameView = findViewById(R.id.game_view)
        tvScore = findViewById(R.id.tv_score)
        tvCountdown = findViewById(R.id.tv_level) // 复用等级TextView显示倒计时
        joystickBg = findViewById(R.id.joystick_bg)
        joystickBall = findViewById(R.id.joystick_ball)
        btnBoost = findViewById(R.id.btn_boost)

        // 游戏初始化
        gameView.startGame()
        gameView.setGameListener { score ->
            // 保存最高分
            val currentHighScore = user?.highScore ?: 0
            if (score > currentHighScore) {
                val updatedUser = user?.copy(highScore = score)
                updatedUser?.let {
                    dbHelper.updateHighScore(account, score)
                    updateServerUser(it)
                }
            }
            // 跳转结果页
            startActivity(Intent(this, ResultActivity::class.java).apply {
                putExtra("username", username)
                putExtra("score", score)
            })
            finish()
        }

        // 初始化摇杆中心
        joystickBg.post {
            joystickBgCenterX = joystickBg.width / 2f
            joystickBgCenterY = joystickBg.height / 2f
            updateJoystickBallPosition(joystickBgCenterX, joystickBgCenterY)
        }

        // 摇杆触摸事件
        joystickBg.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                    joystickIsDragging = true
                    updateJoystickBallAndAngle(event.x, event.y)
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    joystickIsDragging = false
                    updateJoystickBallPosition(joystickBgCenterX, joystickBgCenterY)
                }
            }
            true
        }

        // 加速按钮事件
        btnBoost.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    gameView.boostSpeed(0.8f)
                    btnBoost.setImageResource(R.drawable.speed1)
                    true
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 关键修复：通过 gameView 实例访问 INIT_SPEED
                    val exponent = 1 - 1.toDouble() // 指数转为 Double
                    val baseDelay = (gameView.INIT_SPEED * Math.pow(0.9, exponent)).toInt()
                    gameView.gameThread.updateDelay(baseDelay)
                    btnBoost.setImageResource(R.drawable.speed)
                    true
                }
                else -> false
            }
        }

        // 初始化倒计时显示
        tvCountdown.text = "倒计时：${countdownSeconds}s"
        startCountdown()

        // 分数刷新线程
        Thread {
            while (isThreadRunning) {
                runOnUiThread {
                    tvScore.text = "分数：${gameView.getCurrentScore()}"
                }
                try {
                    Thread.sleep(100)
                } catch (e: InterruptedException) {
                    break
                }
            }
        }.start()
    }

    // 启动倒计时
    private fun startCountdown() {
        countdownThread = Thread {
            while (countdownSeconds > 0 && isThreadRunning) {
                try {
                    Thread.sleep(1000)
                    countdownSeconds--
                    runOnUiThread {
                        tvCountdown.text = "倒计时：${countdownSeconds}s"
                        if (countdownSeconds <= 10) {
                            tvCountdown.setTextColor(resources.getColor(android.R.color.holo_red_dark))
                        }
                    }
                } catch (e: InterruptedException) {
                    break
                }
            }
            // 倒计时结束，结束游戏
            if (isThreadRunning) {
                runOnUiThread {
                    gameView.gameOver()
                }
            }
        }
        countdownThread?.start()
    }

    // 更新服务器用户信息
    private fun updateServerUser(user: User) {
        val updated = RankUtils.updateUser(user, this)
        runOnUiThread {
            if (updated) {
                Toast.makeText(this, "分数已同步到服务器", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "分数同步失败，请检查网络", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 更新摇杆位置和角度
    private fun updateJoystickBallAndAngle(touchX: Float, touchY: Float) {
        val dx = touchX - joystickBgCenterX
        val dy = touchY - joystickBgCenterY
        val distance = hypot(dx, dy)

        val finalX = if (distance > maxBallDistance) {
            joystickBgCenterX + (dx / distance) * maxBallDistance
        } else touchX

        val finalY = if (distance > maxBallDistance) {
            joystickBgCenterY + (dy / distance) * maxBallDistance
        } else touchY

        updateJoystickBallPosition(finalX, finalY)
        val angle = atan2(dy.toDouble(), dx.toDouble()).toFloat()
        gameView.setMoveAngle(angle)
    }

    // 更新摇杆球位置
    private fun updateJoystickBallPosition(x: Float, y: Float) {
        val bgX = joystickBg.x
        val bgY = joystickBg.y
        joystickBall.x = bgX + x - joystickBallRadius
        joystickBall.y = bgY + y - joystickBallRadius
    }

    override fun onPause() {
        super.onPause()
        gameView.pauseGame()
    }

    override fun onDestroy() {
        super.onDestroy()
        isThreadRunning = false
        countdownThread?.interrupt()
        dbHelper.close()
    }
}